package cn.dfun.demo.scdemo.payment.controller;

import cn.dfun.demo.scdemo.common.entity.CommonResult;
import cn.dfun.demo.scdemo.common.entity.Payment;
import cn.dfun.demo.scdemo.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value="/payment/create")
    public CommonResult create(@RequestBody  Payment payment) {
        int result = paymentService.create(payment);
        return result > 0 ? CommonResult.success(result) : CommonResult.fail();
    }

    @GetMapping(value="/payment/get/{id}")
    public CommonResult getById(@PathVariable Long id) {
        Payment payment = paymentService.getById(id);
        String msg = "端口号: " + serverPort;
        return payment != null ? CommonResult.success(msg, payment) : CommonResult.fail();
    }

    @GetMapping(value="/payment/discovery")
    public Object discovery() {
        // 获取服务清单列表
        List<String> services = discoveryClient.getServices();
        for(String element: services) {
            log.info("############element:" + element);
        }
        // 获取实例信息
        List<ServiceInstance> instances = discoveryClient.getInstances("scdemo-payment");
        for(ServiceInstance instance : instances) {
            // 服务名 主机名 端口 uri
            log.info("##########" + instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value="/payment/lb")
    public String lb() {
        return this.serverPort;
    }

    @GetMapping(value="/payment/timeout")
    public String timeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String zipkin() {
        return "hi,zipkin...";
    }
}
